<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>koa | 个人博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="express 和 koa的区别 express 典型的是es5语法 express.Router, 内置了路由系统。 内置中间件， express.staic 对req和res进行了封装。 中间件函数的概念use， 回调嵌套的方式  koa  典型的es6语法 promise来实现的， 非常小，没有多余的内容。 只有一个use方法，在使用的时候可以采用koa 去二次封装来实现   手写koa 1">
<meta property="og:type" content="article">
<meta property="og:title" content="koa">
<meta property="og:url" content="https://gitee.com/wieldy/bailment-blog/2022/03/29/koa/index.html">
<meta property="og:site_name" content="个人博客">
<meta property="og:description" content="express 和 koa的区别 express 典型的是es5语法 express.Router, 内置了路由系统。 内置中间件， express.staic 对req和res进行了封装。 中间件函数的概念use， 回调嵌套的方式  koa  典型的es6语法 promise来实现的， 非常小，没有多余的内容。 只有一个use方法，在使用的时候可以采用koa 去二次封装来实现   手写koa 1">
<meta property="og:locale" content="en_US">
<meta property="article:published_time" content="2022-03-29T14:12:00.000Z">
<meta property="article:modified_time" content="2023-04-23T12:11:43.651Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/bailment-blog/atom.xml" title="个人博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/bailment-blog/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/bailment-blog/css/style.css">

  
    
<link rel="stylesheet" href="/bailment-blog/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 6.3.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/bailment-blog/" id="logo">个人博客</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/bailment-blog/">Home</a>
        
          <a class="main-nav-link" href="/bailment-blog/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/bailment-blog/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/wieldy/bailment-blog"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-koa" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/bailment-blog/2022/03/29/koa/" class="article-date">
  <time class="dt-published" datetime="2022-03-29T14:12:00.000Z" itemprop="datePublished">2022-03-29</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      koa
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="express-和-koa的区别"><a href="#express-和-koa的区别" class="headerlink" title="express 和 koa的区别"></a>express 和 koa的区别</h2><ul>
<li>express 典型的是es5语法 express.Router, 内置了路由系统。 内置中间件， express.staic 对req和res进行了封装。 中间件函数的概念use， 回调嵌套的方式 </li>
<li>koa  典型的es6语法 promise来实现的， 非常小，没有多余的内容。 只有一个use方法，在使用的时候可以采用koa 去二次封装来实现</li>
</ul>
<ul>
<li><p>手写koa</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// koa/index.js</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="built_in">require</span>(<span class="string">&#x27;./lib/application&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/application.js</span></span><br><span class="line"><span class="keyword">const</span> http = <span class="built_in">require</span>(<span class="string">&#x27;http&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> context = <span class="built_in">require</span>(<span class="string">&#x27;./context&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> request = <span class="built_in">require</span>(<span class="string">&#x27;./request&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> response = <span class="built_in">require</span>(<span class="string">&#x27;./response&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">EventEmitter</span> = <span class="built_in">require</span>(<span class="string">&#x27;events&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Stream</span> = <span class="built_in">require</span>(<span class="string">&#x27;stream&#x27;</span>);</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Application</span> <span class="keyword">extends</span> <span class="title class_ inherited__">EventEmitter</span> &#123;</span><br><span class="line">    <span class="title function_">constructor</span>(<span class="params"></span>) &#123;</span><br><span class="line">        <span class="variable language_">super</span>();</span><br><span class="line">        <span class="comment">// this.app = this.context;</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">context</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(context); <span class="comment">// 此context是被共享的</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">request</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(request);</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">response</span> = <span class="title class_">Object</span>.<span class="title function_">create</span>(response); <span class="comment">// 应用的隔离</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">middlewares</span> = [];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">use</span>(<span class="params">middleware</span>) &#123;</span><br><span class="line">        <span class="comment">// this.middleware = middleware;</span></span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">middlewares</span>.<span class="title function_">push</span>(middleware);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">createContext</span>(<span class="params">req, res</span>) &#123;</span><br><span class="line">        <span class="keyword">let</span> context = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">context</span>);</span><br><span class="line">        <span class="keyword">let</span> request = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">request</span>);</span><br><span class="line">        <span class="keyword">let</span> response = <span class="title class_">Object</span>.<span class="title function_">create</span>(<span class="variable language_">this</span>.<span class="property">response</span>);</span><br><span class="line">        context.<span class="property">request</span> = request;</span><br><span class="line">        context.<span class="property">response</span> = response;</span><br><span class="line"></span><br><span class="line">        context.<span class="property">req</span> = context.<span class="property">request</span>.<span class="property">req</span> = req;</span><br><span class="line">        context.<span class="property">res</span> = context.<span class="property">response</span>.<span class="property">res</span> = res;</span><br><span class="line">        <span class="keyword">return</span> context</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">compose</span>(<span class="params">ctx</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> <span class="title function_">dispatch</span> = (<span class="params">i</span>) =&gt; &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="variable language_">this</span>.<span class="property">middlewares</span>.<span class="property">length</span> === i) <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">resolve</span>(<span class="variable language_">this</span>.<span class="property">middlewares</span>[i](ctx, <span class="function">() =&gt;</span> <span class="title function_">dispatch</span>(i + <span class="number">1</span>)))</span><br><span class="line">            &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">                <span class="keyword">return</span> <span class="title class_">Promise</span>.<span class="title function_">reject</span>(e)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">dispatch</span>(<span class="number">0</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    handleRequest = <span class="function">(<span class="params">req, res</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> ctx = <span class="variable language_">this</span>.<span class="title function_">createContext</span>(req, res);</span><br><span class="line">        res.<span class="property">statusCode</span> = <span class="number">404</span>;</span><br><span class="line">        <span class="comment">// this.middleware(ctx); // 内部会设置body的值 </span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="variable language_">this</span>.<span class="title function_">compose</span>(ctx).<span class="title function_">then</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (ctx.<span class="property">body</span> <span class="keyword">instanceof</span> <span class="title class_">Stream</span>) &#123; <span class="comment">// 这里可以对ctx.body的类型进行判断</span></span><br><span class="line"></span><br><span class="line">                <span class="comment">// res.setHeader(&#x27;Content-Type&#x27;, &#x27;application/octet-stream&#x27;);</span></span><br><span class="line">                <span class="comment">// res.setHeader(&#x27;Content-Disposition&#x27;, &#x27;attachment;filename=2018-03-03_15-47-45--2019-0&#x27;)</span></span><br><span class="line">                ctx.<span class="property">body</span>.<span class="title function_">pipe</span>(res)</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> ctx.<span class="property">body</span> === <span class="string">&#x27;object&#x27;</span>) &#123;</span><br><span class="line">                ctx.<span class="property">body</span> = <span class="title class_">JSON</span>.<span class="title function_">stringify</span>(ctx.<span class="property">body</span>)</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                res.<span class="title function_">end</span>(<span class="string">&#x27;Not Found&#x27;</span>)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).<span class="title function_">catch</span>(<span class="function"><span class="params">e</span> =&gt;</span> &#123;</span><br><span class="line">            <span class="comment">// 所有的错误都可以在catch中被捕获</span></span><br><span class="line">            <span class="variable language_">this</span>.<span class="title function_">emit</span>(<span class="string">&#x27;error&#x27;</span>, e)</span><br><span class="line">        &#125;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">listen</span>(<span class="params">...args</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> server = http.<span class="title function_">createServer</span>(<span class="variable language_">this</span>.<span class="property">handleRequest</span>);</span><br><span class="line">        server.<span class="title function_">listen</span>(...args)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// callback -&gt; promise</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="title class_">Application</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/context.js</span></span><br><span class="line"><span class="keyword">const</span> context = &#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">defineGetter</span>(<span class="params">property, key</span>) &#123;</span><br><span class="line">    context.<span class="title function_">__defineGetter__</span>(key, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>[property][key];</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">defineSetter</span>(<span class="params">property, key</span>) &#123;</span><br><span class="line">    context.<span class="title function_">__defineSetter__</span>(key, <span class="keyword">function</span> (<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>[property][key] = value;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;request&#x27;</span>, <span class="string">&#x27;url&#x27;</span>)</span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;request&#x27;</span>, <span class="string">&#x27;query&#x27;</span>)</span><br><span class="line"><span class="title function_">defineGetter</span>(<span class="string">&#x27;response&#x27;</span>, <span class="string">&#x27;body&#x27;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="title function_">defineSetter</span>(<span class="string">&#x27;response&#x27;</span>, <span class="string">&#x27;body&#x27;</span>)</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = context</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/request.js</span></span><br><span class="line"><span class="keyword">const</span> request = &#123;</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">url</span>() &#123;</span><br><span class="line">        <span class="comment">// defineProperty</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">path</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>).<span class="title function_">parse</span>(<span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span>).<span class="property">pathname</span>;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">query</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">require</span>(<span class="string">&#x27;url&#x27;</span>).<span class="title function_">parse</span>(<span class="variable language_">this</span>.<span class="property">req</span>.<span class="property">url</span>, <span class="literal">true</span>).<span class="property">query</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = request</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa/lib/response.js</span></span><br><span class="line"><span class="keyword">const</span> response = &#123;</span><br><span class="line">    <span class="attr">_body</span>: <span class="literal">undefined</span>,</span><br><span class="line">    <span class="keyword">get</span> <span class="title function_">body</span>() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="variable language_">this</span>.<span class="property">_body</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span> <span class="title function_">body</span>(<span class="params">value</span>) &#123;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">res</span>.<span class="property">statusCode</span> = <span class="number">200</span>;</span><br><span class="line">        <span class="variable language_">this</span>.<span class="property">_body</span> = value;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = response</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>middleware</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// middleware/body-parser.js</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">body</span>(<span class="params"></span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">async</span> (ctx, next) =&gt; &#123;</span><br><span class="line">        <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> arr = [];</span><br><span class="line">            ctx.<span class="property">req</span>.<span class="title function_">on</span>(<span class="string">&#x27;data&#x27;</span>, <span class="keyword">function</span> (<span class="params">chunk</span>) &#123;</span><br><span class="line">                arr.<span class="title function_">push</span>(chunk);</span><br><span class="line">            &#125;)</span><br><span class="line">            ctx.<span class="property">req</span>.<span class="title function_">on</span>(<span class="string">&#x27;end&#x27;</span>, <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">                ctx.<span class="property">request</span>.<span class="property">body</span> = <span class="title class_">Buffer</span>.<span class="title function_">concat</span>(arr).<span class="title function_">toString</span>();</span><br><span class="line">                <span class="title function_">resolve</span>()</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;)</span><br><span class="line">        <span class="keyword">return</span> <span class="title function_">next</span>()</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = body</span><br></pre></td></tr></table></figure>
</li>
<li><p>1.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;./koa&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>(); <span class="comment">// const app = express()</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 洋葱模型</span></span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> (ctx) =&gt; &#123; <span class="comment">// req 和 res 在koa中对req和res也进行了封装   request和response （koa自己实现的）  -》 ctx上面</span></span><br><span class="line">    <span class="comment">// req.url  req.method  默认http上面的</span></span><br><span class="line">    <span class="comment">// res.setHeader</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// console.log(ctx.req.url);</span></span><br><span class="line">    <span class="comment">// console.log(ctx.request.req.url);</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// ------</span></span><br><span class="line">    <span class="comment">// console.log(ctx.request.query); // ctx.url == ctx.request.url</span></span><br><span class="line">    <span class="comment">// console.log(ctx.query);</span></span><br><span class="line"></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>)</span><br><span class="line"></span><br><span class="line">    ctx.<span class="property">response</span>.<span class="property">body</span> = <span class="string">&#x27;hello&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>)</span><br><span class="line">    ctx.<span class="property">response</span>.<span class="property">body</span> = <span class="string">&#x27;world&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">body</span>);</span><br><span class="line"></span><br><span class="line">    ctx.<span class="property">body</span> = <span class="string">&#x27;100&#x27;</span>;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">response</span>.<span class="property">body</span>)</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line"><span class="comment">// koa 50%的功能</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>2.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;./koa&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>(); <span class="comment">// const app = express()</span></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="comment">// 在使用koa的时候 需要将所有异步的逻辑全部变成 promise 规定 </span></span><br><span class="line"><span class="comment">//  koa要求next前面 必须要加 await 或者return 否则当前执行的逻辑不会等待后面执行完毕</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 洋葱模型</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="comment">// res.sendFile()</span></span><br><span class="line">    <span class="comment">// ctx.type = &#x27;&#x27;</span></span><br><span class="line">    <span class="comment">// ctx.set(&#x27;Content-Type&#x27;)</span></span><br><span class="line">    ctx.<span class="property">res</span>.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;text/markdown;charset=utf-8&#x27;</span>)</span><br><span class="line">    ctx.<span class="property">body</span> = fs.<span class="title function_">createReadStream</span>(path.<span class="title function_">resolve</span>(__dirname, <span class="string">&#x27;note.md&#x27;</span>))</span><br><span class="line">&#125;)</span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">3</span>);</span><br><span class="line">    <span class="keyword">await</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">            <span class="title function_">resolve</span>()</span><br><span class="line">        &#125;, <span class="number">3000</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">await</span> <span class="title function_">next</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">4</span>)</span><br><span class="line">&#125;)</span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123; <span class="comment">// 这个方法在内部会包装成promise</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">5</span>);</span><br><span class="line">    <span class="title function_">next</span>();</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="number">6</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">on</span>(<span class="string">&#x27;error&#x27;</span>, <span class="keyword">function</span> (<span class="params">e</span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;error&#x27;</span>, e)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 因为express 处理错误靠的是错误处理中间件  promise里面可以自己catch。 设计也是为了错误的统一处理</span></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>);</span><br><span class="line"></span><br></pre></td></tr></table></figure>
</li>
<li><p>3.server.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">Koa</span> = <span class="built_in">require</span>(<span class="string">&#x27;koa&#x27;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> app = <span class="keyword">new</span> <span class="title class_">Koa</span>();</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">&#x27;fs&#x27;</span>).<span class="property">promises</span>;</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">&#x27;path&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> mime = <span class="built_in">require</span>(<span class="string">&#x27;mime&#x27;</span>)</span><br><span class="line"><span class="keyword">const</span> body = <span class="built_in">require</span>(<span class="string">&#x27;./middleware/body-parser&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// koa-router  koa-static koa-session ...</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">static</span>(<span class="params">filepath</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//  mime.types[path.extname(path.join(filepath, ctx.path))]</span></span><br><span class="line">            <span class="comment">// ctx.type = &#x27;text/html;charset=utf-8&#x27;</span></span><br><span class="line">            ctx.<span class="property">res</span>.<span class="title function_">setHeader</span>(<span class="string">&#x27;Content-Type&#x27;</span>, <span class="string">&#x27;xasdasfref&#x27;</span>)</span><br><span class="line">            ctx.<span class="property">res</span>.<span class="title function_">end</span>(<span class="string">&#x27;ok&#x27;</span>)</span><br><span class="line">        &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">            <span class="variable language_">console</span>.<span class="title function_">log</span>(e)</span><br><span class="line">            <span class="keyword">return</span> <span class="title function_">next</span>();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">body</span>())</span><br><span class="line">app.<span class="title function_">use</span>(<span class="title function_">static</span>(__dirname))</span><br><span class="line"><span class="comment">// app.use(async function (ctx, next) &#123;</span></span><br><span class="line"><span class="comment">//     // 用户访问 /login 显示一个登录页面</span></span><br><span class="line"><span class="comment">//     if (ctx.path == &#x27;/login&#x27; &amp;&amp; ctx.method === &#x27;GET&#x27;) &#123;</span></span><br><span class="line"><span class="comment">//         ctx.type = &#x27;text/html;charset=utf-8&#x27;</span></span><br><span class="line"><span class="comment">//         ctx.body = fs.createReadStream(path.resolve(__dirname, &#x27;index.html&#x27;));</span></span><br><span class="line"><span class="comment">//     &#125; else &#123;</span></span><br><span class="line"><span class="comment">//         return next();</span></span><br><span class="line"><span class="comment">//     &#125;</span></span><br><span class="line"><span class="comment">// &#125;)</span></span><br><span class="line">app.<span class="title function_">use</span>(<span class="keyword">async</span> <span class="keyword">function</span> (<span class="params">ctx, next</span>) &#123;</span><br><span class="line">    <span class="comment">// 用户点击登录 将用户填写的信息显示到页面上</span></span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(ctx.<span class="property">path</span>, ctx.<span class="property">method</span>)</span><br><span class="line">    <span class="keyword">if</span> (ctx.<span class="property">path</span> === <span class="string">&#x27;/login&#x27;</span> &amp;&amp; ctx.<span class="property">method</span> === <span class="string">&#x27;POST&#x27;</span>) &#123;</span><br><span class="line">        ctx.<span class="property">body</span> = ctx.<span class="property">request</span>.<span class="property">body</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        ctx.<span class="property">body</span> = <span class="string">&#x27;not found&#x27;</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">app.<span class="title function_">listen</span>(<span class="number">3000</span>)</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;IE=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;/login&quot;</span> <span class="attr">method</span>=<span class="string">&quot;POST&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span>&gt;</span>提交<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/wieldy/bailment-blog/2022/03/29/koa/" data-id="cljmgj1ex000jzc9j5bot8g88" data-title="koa" class="article-share-link">Share</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/bailment-blog/2022/03/29/module/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          module
        
      </div>
    </a>
  
  
    <a href="/bailment-blog/2022/03/29/mongo/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">mongo</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/07/">July 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/06/">June 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/04/">April 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2023/03/">March 2023</a></li><li class="archive-list-item"><a class="archive-list-link" href="/bailment-blog/archives/2022/03/">March 2022</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/bailment-blog/2023/07/03/%E5%B7%A5%E4%BD%9C%E6%97%A5%E5%BF%97/">工作日志</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/29/payMent/">payMent</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/20/%E7%BD%91%E7%BA%A2%E9%9D%A2%E8%AF%95%E9%A2%98/">原理题</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/19/%E5%89%8D%E7%AB%AF%E5%A4%A7%E5%B1%8F%E8%87%AA%E9%80%82%E5%BA%94%E6%96%B9%E6%B3%95/">前端大屏自适应方法</a>
          </li>
        
          <li>
            <a href="/bailment-blog/2023/06/17/10%E4%B8%AAJavaScript%E5%B8%B8%E8%A7%81%E9%AB%98%E7%BA%A7%E7%9F%A5%E8%AF%86%E7%82%B9/">10个JavaScript常见高级知识点</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2023 John Doe<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/bailment-blog/" class="mobile-nav-link">Home</a>
  
    <a href="/bailment-blog/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/bailment-blog/js/jquery-3.4.1.min.js"></script>



  
<script src="/bailment-blog/fancybox/jquery.fancybox.min.js"></script>




<script src="/bailment-blog/js/script.js"></script>





  </div>
</body>
</html>